class ElementController {
  constructor() {
    this.appliedStyles = new Map();
    this.originalStyles = new Map();
    this.HIDE_CLASS = 'element-controller-hidden';
    this.SHOW_CLASS = 'element-controller-shown';
    this.injectedCSS = false;
    this.init();
  }

  init() {
    this.injectCSS();
    this.bindVisibilityChangeHandler();
    
    // 确保DOM完全加载后再次注入CSS
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => {
        this.injectCSS();
      });
    }
  }

  injectCSS() {
    // 移除现有的样式以重新注入
    const existingStyle = document.getElementById('element-controller-styles');
    if (existingStyle) {
      existingStyle.remove();
    }
    
    const style = document.createElement('style');
    style.id = 'element-controller-styles';
    style.textContent = `
      .${this.HIDE_CLASS}, 
      body .${this.HIDE_CLASS}, 
      html .${this.HIDE_CLASS}, 
      * .${this.HIDE_CLASS},
      [class*="${this.HIDE_CLASS}"] {
        display: none !important;
        visibility: hidden !important;
        opacity: 0 !important;
        max-height: 0 !important;
        max-width: 0 !important;
        overflow: hidden !important;
        position: absolute !important;
        left: -9999px !important;
        top: -9999px !important;
        z-index: -9999 !important;
        pointer-events: none !important;
      }
      .${this.SHOW_CLASS}, 
      body .${this.SHOW_CLASS}, 
      html .${this.SHOW_CLASS}, 
      * .${this.SHOW_CLASS},
      [class*="${this.SHOW_CLASS}"] {
        display: block !important;
        visibility: visible !important;
        opacity: 1 !important;
        position: static !important;
        left: auto !important;
        top: auto !important;
        z-index: auto !important;
        pointer-events: auto !important;
      }
      .element-controller-highlight {
        outline: 3px solid #ff4444 !important;
        outline-offset: 2px !important;
        background: rgba(255, 68, 68, 0.2) !important;
        position: relative !important;
        z-index: 9999 !important;
      }
    `;
    
    // 尝试多种方式插入样式
    const target = document.head || document.documentElement || document.body;
    
    if (target) {
      target.appendChild(style);
      
      // 再次确保样式在最后
      setTimeout(() => {
        if (style.parentNode) {
          style.parentNode.appendChild(style);
        }
      }, 100);
    }
    
    this.injectedCSS = true;
  }

  bindVisibilityChangeHandler() {
    document.addEventListener('visibilitychange', () => {
      if (!document.hidden) {
        this.reapplyAllRules();
      }
    });
  }

  validateSelector(selector) {
    if (!selector || typeof selector !== 'string') {
      return { valid: false, error: 'Selector must be a non-empty string' };
    }

    if (selector.trim().length === 0) {
      return { valid: false, error: 'Selector cannot be empty' };
    }

    if (selector.length > 1000) {
      return { valid: false, error: 'Selector is too long (max 1000 characters)' };
    }

    try {
      document.querySelector(selector);
      return { valid: true };
    } catch (error) {
      return { valid: false, error: `Invalid CSS selector: ${error.message}` };
    }
  }

  getMatchCount(selector) {
    try {
      const validation = this.validateSelector(selector);
      if (!validation.valid) {
        return { count: 0, error: validation.error };
      }

      const elements = document.querySelectorAll(selector);
      return { count: elements.length };
    } catch (error) {
      return { count: 0, error: error.message };
    }
  }

  getMatchingElements(selector) {
    try {
      const validation = this.validateSelector(selector);
      if (!validation.valid) {
        return { elements: [], error: validation.error };
      }

      const elements = Array.from(document.querySelectorAll(selector));
      return { elements };
    } catch (error) {
      return { elements: [], error: error.message };
    }
  }

  highlightElements(selector, duration = 3000) {
    
    const result = this.getMatchingElements(selector);

    if (result.error) {
      return result;
    }
    
    if (result.elements.length === 0) {
      return result;
    }


    result.elements.forEach((element, index) => {

      // 检查元素是否已经有高亮类
      const hadHighlight = element.classList.contains('element-controller-highlight');

      element.classList.add('element-controller-highlight');
      
      // 验证类是否被添加
      const hasHighlight = element.classList.contains('element-controller-highlight');

      // 检查计算样式
      const computedStyle = window.getComputedStyle(element);

      try {
        element.scrollIntoView({ 
          behavior: 'smooth', 
          block: 'center',
          inline: 'center' 
        });
      } catch (scrollError) {
        console.error(`ElementController: Error scrolling element ${index}:`, scrollError);
      }
    });

    if (duration > 0) {
      setTimeout(() => {
        result.elements.forEach((element, index) => {
          if (element && element.classList) {
            element.classList.remove('element-controller-highlight');
          }
        });
      }, duration);
    }

    const finalResult = { count: result.elements.length };
    return finalResult;
  }

  removeHighlight(selector) {
    try {
      const elements = document.querySelectorAll(selector);
      elements.forEach(element => {
        element.classList.remove('element-controller-highlight');
      });
      return true;
    } catch (error) {
      console.error('Error removing highlight:', error);
      return false;
    }
  }

  applyElementRule(elementRule) {

    if (!elementRule || !elementRule.selector || !elementRule.action) {
      return { success: false, error: 'Invalid element rule' };
    }

    const { selector, action, id } = elementRule;

    const validation = this.validateSelector(selector);

    if (!validation.valid) {
      return { success: false, error: validation.error };
    }

    try {
      const elements = document.querySelectorAll(selector);

      let appliedCount = 0;

      elements.forEach((element, index) => {
        this.storeOriginalStyle(element, id);
        
        if (action === 'hide') {
          this.hideElement(element);
          appliedCount++;
        } else if (action === 'show') {
          this.showElement(element);
          appliedCount++;
        }
      });

      this.appliedStyles.set(id, { selector, action, appliedCount });
      
      const result = { 
        success: true, 
        appliedCount,
        totalFound: elements.length
      };
      
      return result;
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  removeElementRule(ruleId) {
    if (!this.appliedStyles.has(ruleId)) {
      return { success: false, error: 'Rule not found' };
    }

    const rule = this.appliedStyles.get(ruleId);
    
    try {
      const elements = document.querySelectorAll(rule.selector);
      elements.forEach(element => {
        this.restoreOriginalStyle(element, ruleId);
      });

      this.appliedStyles.delete(ruleId);
      this.cleanupOriginalStyles(ruleId);
      
      return { success: true };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  hideElement(element) {
    // 直接使用最强力的内联样式隐藏
    element.style.cssText = `
      display: none !important;
      visibility: hidden !important;
      opacity: 0 !important;
      position: absolute !important;
      left: -9999px !important;
      top: -9999px !important;
      width: 0 !important;
      height: 0 !important;
      overflow: hidden !important;
      z-index: -9999 !important;
    `;
    
    // 同时添加CSS类作为标记
    element.classList.remove(this.SHOW_CLASS);
    element.classList.add(this.HIDE_CLASS);
    
    // 添加数据属性作为标记
    element.setAttribute('data-element-controller', 'hidden');
    
  }

  showElement(element) {
    // 移除所有隐藏样式
    element.style.cssText = '';
    
    // 移除CSS类
    element.classList.remove(this.HIDE_CLASS);
    element.classList.add(this.SHOW_CLASS);
    
    // 移除数据属性
    element.removeAttribute('data-element-controller');
    
  }

  storeOriginalStyle(element, ruleId) {
    const key = this.getElementKey(element, ruleId);
    if (!this.originalStyles.has(key)) {
      // 获取计算样式作为参考
      const computedStyle = window.getComputedStyle(element);
      
      this.originalStyles.set(key, {
        display: element.style.display || computedStyle.display,
        visibility: element.style.visibility || computedStyle.visibility,
        opacity: element.style.opacity || computedStyle.opacity,
        classes: Array.from(element.classList).filter(cls => 
          !cls.startsWith('element-controller-')
        ),
        // 记录是否已经隐藏
        wasHidden: computedStyle.display === 'none' || computedStyle.visibility === 'hidden'
      });
    }
  }

  restoreOriginalStyle(element, ruleId) {
    const key = this.getElementKey(element, ruleId);
    const original = this.originalStyles.get(key);
    
    // 移除我们的CSS类
    element.classList.remove(this.HIDE_CLASS, this.SHOW_CLASS);
    
    // 移除我们设置的内联样式
    element.style.removeProperty('display');
    element.style.removeProperty('visibility');
    element.style.removeProperty('opacity');
    
    if (original) {
      // 恢复原始样式（如果有的话）
      if (original.display) {
        element.style.display = original.display;
      }
      if (original.visibility) {
        element.style.visibility = original.visibility;
      }
      
      this.originalStyles.delete(key);
    }
  }

  getElementKey(element, ruleId) {
    return `${ruleId}_${this.getElementIdentifier(element)}`;
  }

  getElementIdentifier(element) {
    if (element.id) return `id_${element.id}`;
    
    const rect = element.getBoundingClientRect();
    return `pos_${Math.round(rect.top)}_${Math.round(rect.left)}_${element.tagName}`;
  }

  cleanupOriginalStyles(ruleId) {
    const keysToDelete = [];
    for (const key of this.originalStyles.keys()) {
      if (key.startsWith(`${ruleId}_`)) {
        keysToDelete.push(key);
      }
    }
    keysToDelete.forEach(key => this.originalStyles.delete(key));
  }

  reapplyAllRules() {
    for (const [ruleId, rule] of this.appliedStyles.entries()) {
      try {
        const elements = document.querySelectorAll(rule.selector);
        elements.forEach(element => {
          if (rule.action === 'hide') {
            this.hideElement(element);
          } else if (rule.action === 'show') {
            this.showElement(element);
          }
        });
      } catch (error) {
        console.error(`Error reapplying rule ${ruleId}:`, error);
      }
    }
  }

  clearAllRules() {
    for (const ruleId of this.appliedStyles.keys()) {
      this.removeElementRule(ruleId);
    }
  }

  getAppliedRulesInfo() {
    const info = [];
    for (const [ruleId, rule] of this.appliedStyles.entries()) {
      try {
        const currentCount = document.querySelectorAll(rule.selector).length;
        info.push({
          ruleId,
          selector: rule.selector,
          action: rule.action,
          appliedCount: rule.appliedCount,
          currentCount
        });
      } catch (error) {
        info.push({
          ruleId,
          selector: rule.selector,
          action: rule.action,
          appliedCount: rule.appliedCount,
          currentCount: 0,
          error: error.message
        });
      }
    }
    return info;
  }

  testSelector(selector) {
    const validation = this.validateSelector(selector);
    if (!validation.valid) {
      return validation;
    }

    const matchResult = this.getMatchCount(selector);
    return {
      valid: true,
      count: matchResult.count,
      error: matchResult.error
    };
  }

  // 调试函数
  debugElementRule(selector, action = 'hide') {

    try {
      const elements = document.querySelectorAll(selector);

      elements.forEach((element, index) => {

        
        if (action === 'hide') {
          this.hideElement(element);
        }
      });
      
      return { success: true, count: elements.length };
    } catch (error) {
      console.error('Debug failed:', error);
      return { success: false, error: error.message };
    }
  }
}

if (typeof window !== 'undefined') {
  window.ElementController = ElementController;
}